﻿Imports System.Globalization
Partial Public Class E_PayManual
    Inherits System.Web.UI.Page

    Dim clsGet As New ClassFunctionGetData
    Dim clsfc As New ClassFunction
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not (IsPostBack) Then
            If Not (Session("PayinBooking") Is Nothing) Then
                Dim dt As DataTable = clsGet.Get_MatFor_Sale_Order(Session("PayinBooking").ToString().Split("$")(0), Session("PayinBooking").ToString().Split("$")(1))
                Dim Vat As String = ""
                Dim dsConfig As DataSet = Session("Config")
                If (dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(1) = "00") Then
                    Vat = CInt(dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(0)).ToString()
                Else
                    Vat = dsConfig.Tables(0).Rows(0).Item("Vat").ToString()
                End If
                ViewState("VAT") = Vat
                Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(Session("PayinBooking").ToString().Split("$")(0))

                Dim HTML As String = ""
                HTML = Gen_Report(dsConfig.Tables(0).Rows(0).Item("Head_Report_Compute"), Session("MAGENT_NAME_BULK") & "", dsBooking.Tables(0).Rows(0).Item("Vehicle_Text"), dsBooking.Tables(0).Rows(0).Item("Product_name"), dsBooking.Tables(0).Rows(0).Item("Vehicle_DWT"), dsBooking.Tables(0).Rows(0).Item("Vehicle_LOA"), dsBooking.Tables(0).Rows(0).Item("Product_Amount"), dsBooking.Tables(0).Rows(0).Item("Vehicle_Draft"), Gen_Body(Vat, dt), dsBooking.Tables(0).Rows(0).Item("Vehicle_GRT"))
                Literal1.Text = HTML

                Dim ds As DataTable = clsGet.Get_Bank("")
                If (ds.Rows.Count > 0) Then
                    With ddlBank
                        .ClearSelection()
                        .Items.Clear()
                        .DataTextField = "Bank_Name"
                        .DataValueField = "Bank_SAP"
                        .DataSource = ds
                        .DataBind()
                        .Items.Insert(0, "<--กรุณาเลือกธนาคาร-->")
                        .Items(0).Value = "0"
                    End With
                End If
                ddlGL_Account.Items.Insert(0, "<--กรุณาทำการเลือกธนาคาร-->")
                ddlGL_Account.Items(0).Value = "0"
            End If

        End If
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Session("PayinBooking") = Nothing
        Session("MAGENT_NAME_BULK") = Nothing
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " parent.closeModal('X');", True)
    End Sub

    Private Sub btnPayin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPayin.Click
        If (ddlBank.SelectedValue = "0") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือกธนาคารที่ต้องการทำการชำระเงิน');", True)
            Exit Sub
        ElseIf (ddlGL_Account.SelectedValue = "0") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการเลือก GL Account ที่ต้องการทำการชำระเงิน');", True)
            Exit Sub
        ElseIf (ddlBank.SelectedValue = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ธนาคารนี้ยังไม่เปิดให้ใช้งาน');", True)
            Exit Sub
        ElseIf (txtDate.Text.Trim() = "") Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาระบุวันที่ลูกค้าชำระเงิน');", True)
            Exit Sub
        ElseIf (CDate(ClassFunctionGetData.CDateT(txtDate.Text)) > CDate(Date.Now.ToString("dd MMM yyyy", New CultureInfo("en-US")))) Then
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ระบุวันที่ไม่ถูกต้อง');", True)
            Exit Sub
        End If
        If (radioPay.SelectedValue = "CH") Then
            If (txtCH.Text.Trim() = "") Then
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('กรุณาทำการระบุรายละเอียด เช็ค');", True)
                Exit Sub
            End If
        End If
        Dim Bill_Date As String
        Dim Bank As String = "TR " & ddlBank.SelectedValue
        Dim ClassSAP As New Class_SAP
        Dim SAP_Data As Object = ClassSAP.SAP_OPEN()
        Dim CheckCreditLimit As Boolean = True
        Dim dt As DataTable = clsGet.Get_MatFor_Sale_Order(Session("PayinBooking").ToString.Split("$")(0), Session("PayinBooking").ToString.Split("$")(1))
        Dim Iport_Number As String = clsGet.Get_IportNumber()
        Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) - 1).ToString("000")
        Dim dsBooking As DataSet = clsGet.Get_BookingOneRecord(Session("PayinBooking").ToString.Split("$")(0))
        Dim BillTo As String = ""
        If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
            BillTo = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
        End If
        Dim Plant As String = "1104"
        If (dsBooking.Tables(0).Rows(0).Item("PORT") & "" = "L") Then
            Plant = "1103"
        End If
        Dim Item_Text As String = ""
        If (radioPay.SelectedValue = "CH") Then
            Item_Text = "CH " & txtCH.Text
        Else
            Item_Text = "TR " & ddlBank.SelectedValue
        End If

        '***************************************
        'Parameter For Division 11

        Dim Customer11 As SAP_IPORT.ZBAPI_CUSTOMER
        Dim CustomerTable11_0 As New SAP_IPORT.ZBAPI_CUSTOMERTable
        Dim CustomerTable11_1 As New SAP_IPORT.ZBAPI_CUSTOMERTable
        Dim CustomerTable11_5 As New SAP_IPORT.ZBAPI_CUSTOMERTable
        Dim SumAmount11_0 As Double = "0"
        Dim WHTAmount11_0 As Double = "0.00"
        Dim SumAmount11_1 As Double = "0"
        Dim WHTAmount11_1 As Double = "0.00"
        Dim SumAmount11_5 As Double = "0"
        Dim WHTAmount11_5 As Double = "0.00"
        Dim ZBABI_VT11 As New SAP_IPORT.ZBAPI_VAT
        Dim ZBABI_BK11 As New SAP_IPORT.ZBAPI_BANK
        Dim ZBABI_HD11 As New SAP_IPORT.ZBAPI_HEADER
        Dim BABITable11 As New SAP_IPORT.BAPIRET1Table
        Dim Ex_Bukrs11 As String = ""
        Dim Ex_Gjahr11 As String = ""
        Dim Ex_Belnr11 As String = ""

        Dim BABIHEADER11 As New SAP_IPORT.ZBAPI_SALES_HEADER
        Dim EX_SALES_NO11 As String = ""
        Dim EX_BILL_NO11 As String = ""
        Dim EX_BUKRS11_Cash As String = ""
        Dim EX_BELNR11_Cash As String = ""
        Dim EX_GJAHR11_Cash As String = ""
        Dim BABIONETIME11 As New SAP_IPORT.ZBAPI_SALES_ONETIME
        Dim BABI_SALE11 As SAP_IPORT.ZBAPI_SALES_ITEMS
        Dim SALE_TABLE11_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE11_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE11_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim BABITable11_Cash As New SAP_IPORT.BAPIRET1Table

        '******************************************

        '***************************************
        'Parameter For Division 12
        Dim Customer12 As SAP_IPORT.ZBAPI_CUSTOMER
        Dim CustomerTable12_0 As New SAP_IPORT.ZBAPI_CUSTOMERTable
        Dim CustomerTable12_1 As New SAP_IPORT.ZBAPI_CUSTOMERTable
        Dim CustomerTable12_5 As New SAP_IPORT.ZBAPI_CUSTOMERTable
        Dim SumAmount12_0 As Double = "0"
        Dim WHTAmount12_0 As Double = "0.00"
        Dim SumAmount12_1 As Double = "0"
        Dim WHTAmount12_1 As Double = "0.00"
        Dim SumAmount12_5 As Double = "0"
        Dim WHTAmount12_5 As Double = "0.00"
        Dim ZBABI_VT12 As New SAP_IPORT.ZBAPI_VAT
        Dim ZBABI_BK12 As New SAP_IPORT.ZBAPI_BANK
        Dim ZBABI_HD12 As New SAP_IPORT.ZBAPI_HEADER
        Dim BABITable12 As New SAP_IPORT.BAPIRET1Table
        Dim Ex_Bukrs12 As String = ""
        Dim Ex_Gjahr12 As String = ""
        Dim Ex_Belnr12 As String = ""

        Dim BABIHEADER12 As New SAP_IPORT.ZBAPI_SALES_HEADER
        Dim EX_SALES_NO12 As String = ""
        Dim EX_BILL_NO12 As String = ""
        Dim EX_BUKRS12_Cash As String = ""
        Dim EX_BELNR12_Cash As String = ""
        Dim EX_GJAHR12_Cash As String = ""
        Dim BABIONETIME12 As New SAP_IPORT.ZBAPI_SALES_ONETIME
        Dim BABI_SALE12 As SAP_IPORT.ZBAPI_SALES_ITEMS
        Dim SALE_TABLE12_0 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE12_1 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim SALE_TABLE12_5 As New SAP_IPORT.ZBAPI_SALES_ITEMSTable
        Dim BABITable12_Cash As New SAP_IPORT.BAPIRET1Table


        '******************************************
        For Each dr As DataRow In dt.Rows
            'ทำการแยกเฉพาะ Division เท่านั้นเพราะลูกค้าได้ทำการแยกตามคนที่เข้ามาแล้ว
            If (dr.Item("Division") = "11") Then

                Dim Target_QU As String = dr.Item("BASE_UOM")
                Dim Target_Qty As String = ""
                Dim Price As String = ""
                If (Target_QU = "JOB") Then
                    Target_Qty = "1"
                    Price = dr.Item("data4")
                Else
                    Target_Qty = (CDbl(dr.Item("data4")) / CDbl(dr.Item("data2"))).ToString("############0.00")
                    Price = dr.Item("data2")
                End If
                If (dr.Item("TAXCLASS") = "0") Then
                    SumAmount11_0 = SumAmount11_0 + CDbl(dr.Item("data4"))
                    If (dr.Item("MAT_WHT") & "" = "01") Or (dr.Item("MAT_WHT") & "" = "02") Or (dr.Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHTAmount11_0 = (WHTAmount11_0 + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "04") Or (dr.Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHTAmount11_0 = (WHTAmount11_0 + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "06") Or (dr.Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHTAmount11_0 = (WHTAmount11_0 + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If


                    Customer11 = New SAP_IPORT.ZBAPI_CUSTOMER
                    Customer11.Customer = CInt(Session("PayinBooking").ToString().Split("$")(1))
                    Customer11.Amount = dr.Item("data4")
                    Customer11.Item_Text = dr.Item("MAT_NAME")
                    Customer11.Material = CInt(dr.Item("Material")).ToString()
                    Customer11.Price = Price
                    Customer11.Quantity = Target_Qty
                    Customer11.Unit = Target_QU
                    Customer11.Wht_Code = dr.Item("MAT_WHT")

                    CustomerTable11_0.Insert(0, Customer11)

                    BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE11.Material = dr.Item("Material")
                    BABI_SALE11.Plant = Plant
                    BABI_SALE11.Target_Qty = Target_Qty
                    BABI_SALE11.Target_Qu = Target_QU
                    BABI_SALE11.Cond_Type = ""
                    BABI_SALE11.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE11.Amount = LowRate
                            BABI_SALE11.Condvalue = LowRate
                        Else
                            BABI_SALE11.Amount = Price
                            BABI_SALE11.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE11.Amount = Price
                        BABI_SALE11.Condvalue = "0"
                    End Try

                    SALE_TABLE11_0.Insert(0, BABI_SALE11)
                ElseIf (dr.Item("TAXCLASS") = "1") Then
                    SumAmount11_1 = SumAmount11_1 + CDbl(dr.Item("data4"))
                    If (dr.Item("MAT_WHT") & "" = "01") Or (dr.Item("MAT_WHT") & "" = "02") Or (dr.Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHTAmount11_1 = (WHTAmount11_1 + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "04") Or (dr.Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHTAmount11_1 = (WHTAmount11_1 + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "06") Or (dr.Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHTAmount11_1 = (WHTAmount11_1 + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If


                    Customer11 = New SAP_IPORT.ZBAPI_CUSTOMER
                    Customer11.Customer = CInt(Session("PayinBooking").ToString().Split("$")(1))
                    Customer11.Amount = dr.Item("data4")
                    Customer11.Item_Text = dr.Item("MAT_NAME")
                    Customer11.Material = CInt(dr.Item("Material")).ToString()
                    Customer11.Price = Price
                    Customer11.Quantity = Target_Qty
                    Customer11.Unit = Target_QU
                    Customer11.Wht_Code = dr.Item("MAT_WHT")

                    CustomerTable11_1.Insert(0, Customer11)

                    BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE11.Material = dr.Item("Material")
                    BABI_SALE11.Plant = Plant
                    BABI_SALE11.Target_Qty = Target_Qty
                    BABI_SALE11.Target_Qu = Target_QU
                    BABI_SALE11.Cond_Type = ""
                    BABI_SALE11.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE11.Amount = LowRate
                            BABI_SALE11.Condvalue = LowRate
                        Else
                            BABI_SALE11.Amount = Price
                            BABI_SALE11.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE11.Amount = Price
                        BABI_SALE11.Condvalue = "0"
                    End Try

                    SALE_TABLE11_1.Insert(0, BABI_SALE11)
                ElseIf (dr.Item("TAXCLASS") = "5") Then
                    SumAmount11_5 = SumAmount11_5 + CDbl(dr.Item("data4"))
                    If (dr.Item("MAT_WHT") & "" = "01") Or (dr.Item("MAT_WHT") & "" = "02") Or (dr.Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHTAmount11_5 = (WHTAmount11_5 + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "04") Or (dr.Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHTAmount11_5 = (WHTAmount11_5 + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "06") Or (dr.Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHTAmount11_5 = (WHTAmount11_5 + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If


                    Customer11 = New SAP_IPORT.ZBAPI_CUSTOMER
                    Customer11.Customer = CInt(Session("PayinBooking").ToString().Split("$")(1))
                    Customer11.Amount = dr.Item("data4")
                    Customer11.Item_Text = dr.Item("MAT_NAME")
                    Customer11.Material = CInt(dr.Item("Material")).ToString()
                    Customer11.Price = Price
                    Customer11.Quantity = Target_Qty
                    Customer11.Unit = Target_QU
                    Customer11.Wht_Code = dr.Item("MAT_WHT")

                    CustomerTable11_5.Insert(0, Customer11)

                    BABI_SALE11 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE11.Material = dr.Item("Material")
                    BABI_SALE11.Plant = Plant
                    BABI_SALE11.Target_Qty = Target_Qty
                    BABI_SALE11.Target_Qu = Target_QU
                    BABI_SALE11.Cond_Type = ""
                    BABI_SALE11.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE11.Amount = LowRate
                            BABI_SALE11.Condvalue = LowRate
                        Else
                            BABI_SALE11.Amount = Price
                            BABI_SALE11.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE11.Amount = Price
                        BABI_SALE11.Condvalue = "0"
                    End Try

                    SALE_TABLE11_5.Insert(0, BABI_SALE11)
                End If


            Else

                Dim Target_QU As String = dr.Item("BASE_UOM")
                Dim Target_Qty As String = ""
                Dim Price As String = ""
                If (Target_QU = "JOB") Then
                    Target_Qty = "1"
                    Price = dr.Item("data4")
                Else
                    Target_Qty = (CDbl(dr.Item("data4")) / CDbl(dr.Item("data2"))).ToString("############0.00")
                    Price = dr.Item("data2")
                End If
                If (dr.Item("TAXCLASS") = "0") Then
                    SumAmount12_0 = SumAmount12_0 + CDbl(dr.Item("data4"))
                    If (dr.Item("MAT_WHT") & "" = "01") Or (dr.Item("MAT_WHT") & "" = "02") Or (dr.Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHTAmount12_0 = (WHTAmount12_0 + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "04") Or (dr.Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHTAmount12_0 = (WHTAmount12_0 + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "06") Or (dr.Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHTAmount12_0 = (WHTAmount12_0 + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If


                    Customer12 = New SAP_IPORT.ZBAPI_CUSTOMER
                    Customer12.Customer = CInt(Session("PayinBooking").ToString().Split("$")(1))
                    Customer12.Amount = dr.Item("data4")
                    Customer12.Item_Text = dr.Item("MAT_NAME")
                    Customer12.Material = CInt(dr.Item("Material")).ToString()
                    Customer12.Price = Price
                    Customer12.Quantity = Target_Qty
                    Customer12.Unit = Target_QU
                    Customer12.Wht_Code = dr.Item("MAT_WHT")

                    CustomerTable12_0.Insert(0, Customer12)

                    BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE12.Material = dr.Item("Material")
                    BABI_SALE12.Plant = Plant
                    BABI_SALE12.Target_Qty = Target_Qty
                    BABI_SALE12.Target_Qu = Target_QU
                    BABI_SALE12.Cond_Type = ""
                    BABI_SALE12.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE12.Amount = LowRate
                            BABI_SALE12.Condvalue = LowRate
                        Else
                            BABI_SALE12.Amount = Price
                            BABI_SALE12.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE12.Amount = Price
                        BABI_SALE12.Condvalue = "0"
                    End Try

                    SALE_TABLE12_0.Insert(0, BABI_SALE12)
                ElseIf (dr.Item("TAXCLASS") = "1") Then
                    SumAmount12_1 = SumAmount12_1 + CDbl(dr.Item("data4"))
                    If (dr.Item("MAT_WHT") & "" = "01") Or (dr.Item("MAT_WHT") & "" = "02") Or (dr.Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHTAmount12_1 = (WHTAmount12_1 + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "04") Or (dr.Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHTAmount12_1 = (WHTAmount12_1 + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "06") Or (dr.Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHTAmount12_1 = (WHTAmount12_1 + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If


                    Customer12 = New SAP_IPORT.ZBAPI_CUSTOMER
                    Customer12.Customer = CInt(Session("PayinBooking").ToString().Split("$")(1))
                    Customer12.Amount = dr.Item("data4")
                    Customer12.Item_Text = dr.Item("MAT_NAME")
                    Customer12.Material = CInt(dr.Item("Material")).ToString()
                    Customer12.Price = Price
                    Customer12.Quantity = Target_Qty
                    Customer12.Unit = Target_QU
                    Customer12.Wht_Code = dr.Item("MAT_WHT")

                    CustomerTable12_1.Insert(0, Customer12)

                    BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE12.Material = dr.Item("Material")
                    BABI_SALE12.Plant = Plant
                    BABI_SALE12.Target_Qty = Target_Qty
                    BABI_SALE12.Target_Qu = Target_QU
                    BABI_SALE12.Cond_Type = ""
                    BABI_SALE12.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE12.Amount = LowRate
                            BABI_SALE12.Condvalue = LowRate
                        Else
                            BABI_SALE12.Amount = Price
                            BABI_SALE12.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE12.Amount = Price
                        BABI_SALE12.Condvalue = "0"
                    End Try

                    SALE_TABLE12_1.Insert(0, BABI_SALE12)
                ElseIf (dr.Item("TAXCLASS") = "5") Then
                    SumAmount12_5 = SumAmount12_5 + CDbl(dr.Item("data4"))
                    If (dr.Item("MAT_WHT") & "" = "01") Or (dr.Item("MAT_WHT") & "" = "02") Or (dr.Item("MAT_WHT") & "" = "03") Then
                        '1%
                        WHTAmount12_5 = (WHTAmount12_5 + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "04") Or (dr.Item("MAT_WHT") & "" = "05") Then
                        '3%
                        WHTAmount12_5 = (WHTAmount12_5 + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    ElseIf (dr.Item("MAT_WHT") & "" = "06") Or (dr.Item("MAT_WHT") & "" = "22") Then
                        '5%
                        WHTAmount12_5 = (WHTAmount12_5 + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                    End If


                    Customer12 = New SAP_IPORT.ZBAPI_CUSTOMER
                    Customer12.Customer = CInt(Session("PayinBooking").ToString().Split("$")(1))
                    Customer12.Amount = dr.Item("data4")
                    Customer12.Item_Text = dr.Item("MAT_NAME")
                    Customer12.Material = CInt(dr.Item("Material")).ToString()
                    Customer12.Price = Price
                    Customer12.Quantity = Target_Qty
                    Customer12.Unit = Target_QU
                    Customer12.Wht_Code = dr.Item("MAT_WHT")
          
                    CustomerTable12_5.Insert(0, Customer12)



                    BABI_SALE12 = New SAP_IPORT.ZBAPI_SALES_ITEMS
                    BABI_SALE12.Material = dr.Item("Material")
                    BABI_SALE12.Plant = Plant
                    BABI_SALE12.Target_Qty = Target_Qty
                    BABI_SALE12.Target_Qu = Target_QU
                    BABI_SALE12.Cond_Type = ""
                    BABI_SALE12.Discount = "0"
                    Try
                        Dim dtLowRate As DataTable = clsGet.Get_ROWRATE_MAT(dr.Item("Material"))
                        Dim LowRate As Double = "0"
                        Dim chkROw As Boolean = False
                        For Each dL As DataRow In dtLowRate.Rows
                            If (CDbl(dr.Item("data4")) = CDbl(dL.Item("LowRate"))) Then
                                LowRate = dr.Item("data4")
                                chkROw = True
                                Exit For
                            End If
                        Next
                        If (chkROw) Then
                            BABI_SALE12.Amount = LowRate
                            BABI_SALE12.Condvalue = LowRate
                        Else
                            BABI_SALE12.Amount = Price
                            BABI_SALE12.Condvalue = "0"
                        End If
                    Catch ex As Exception
                        BABI_SALE12.Amount = Price
                        BABI_SALE12.Condvalue = "0"
                    End Try

                    SALE_TABLE12_5.Insert(0, BABI_SALE12)
                End If

            End If

        Next

        Dim clsDB As New ClassDatabase()
        Dim conn As New System.Data.SqlClient.SqlConnection(connString)
        Dim condition As Boolean = True
        Dim tran As System.Data.SqlClient.SqlTransaction = Nothing
        Application.Lock()
        conn.Open()
        tran = clsDB.BeginTran(conn)

        If (CustomerTable11_0.Count > 0) Then
            'มี Mat ที่ใช้ Division 11
            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
            ZBABI_VT11.Amount = SumAmount11_0.ToString("############.00")
            ZBABI_VT11.Vat = ((SumAmount11_0 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")
            ' ZBABI_BK11.Amount = (CDbl(SumAmount11_0 + CDbl(((SumAmount11_0 * CDbl(ViewState("VAT"))) / 100).ToString("############.00"))) - WHTAmount11_0).ToString("############.00")

            ZBABI_BK11.Amount = (CDbl(SumAmount11_0 + CDbl(((SumAmount11_0 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")))).ToString("############.00")
            ZBABI_BK11.Gl_Account = ddlGL_Account.SelectedValue  'เลขบัญชีต้องดึงจาก Web service Bank
            ZBABI_BK11.Item_Text = Item_Text

            If (radioPay.SelectedValue = "CH") Then
                ZBABI_BK11.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")  '"20100921"
                Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
            Else
                ZBABI_BK11.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"
                Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
            End If
            ZBABI_HD11.Bupla = "N014"
            ZBABI_HD11.Doc_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd") '"20100730"
            ZBABI_HD11.Header_Txt = "R|" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") '"R|LEO GLORY"
            ZBABI_HD11.Pstng_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd") '"20100921"

            SAP_Data.Zbapi_Iport_Advanced_Payment(ZBABI_BK11, ZBABI_HD11, Iport_Number, BillTo, ZBABI_VT11, Ex_Belnr11, Ex_Bukrs11, Ex_Gjahr11, CustomerTable11_1, BABITable11)
            Dim xx As String = ""
            For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                xx &= dr.Message & " "
            Next
            If (Ex_Belnr11 <> "") And (Ex_Bukrs11 <> "") And (Ex_Gjahr11 <> "") Then
                'Advanced Payment ผ่าน
                Dim Bill_To As String = ""
                Dim Sold_To As String = ""
                If (Session("PayinBooking").ToString().Split("$")(1) = dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                    Sold_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                    Bill_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                    If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
                        Bill_To = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
                    End If
                Else
                    Sold_To = Session("PayinBooking").ToString().Split("$")(1)
                    Bill_To = Session("PayinBooking").ToString().Split("$")(1)
                End If

                BABIHEADER11.Doc_Type = "ZSRC"
                If (radioPay.SelectedValue = "CH") Then
                    BABIHEADER11.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Else
                    BABIHEADER11.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                End If
                BABIHEADER11.Sold_To = Sold_To
                BABIHEADER11.Bill_To = Bill_To
                BABIHEADER11.Ship_Name = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                BABIHEADER11.Division = "11"

                SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales(Bill_Date, "", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BELNR11_Cash, EX_BILL_NO11, EX_BUKRS11_Cash, EX_GJAHR11_Cash, EX_SALES_NO11, BABITable11_Cash, SALE_TABLE11_0)
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11_Cash
                    xx &= dr.Message & " "
                Next
                If (EX_SALES_NO11 <> "") Then
                    'Insert Advanced Payment

                    If (clsfc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                            If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Advanced_Payment", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            If (clsfc.InsertSAP_Advanced_Payment(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, ZBABI_BK11.Gl_Account, ZBABI_BK11.Item_Text, ZBABI_BK11.Value_Date, ZBABI_HD11.Bupla, ZBABI_HD11.Doc_Date, ZBABI_HD11.Header_Txt, ZBABI_HD11.Pstng_Date, ZBABI_VT11.Amount, ZBABI_VT11.Vat, Ex_Bukrs11, Ex_Gjahr11, Ex_Belnr11, WHTAmount11_0, "M", conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.ZBAPI_CUSTOMER In CustomerTable11_0
                                    If (dr.Material <> "") Then
                                        If (clsfc.InsertSAP_Advanced_Payment_Material(Iport_Number, dr.Customer, dr.Amount, dr.Item_Text, dr.Material, dr.Price, dr.Quantity, dr.Unit, dr.Wht_Code, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    End If
                                Next
                            Else
                                condition = False
                            End If
                        End If
                    Else
                        condition = False
                    End If

                    'Insert Cash Sale
                    Dim chkcredit As Boolean = True   ' True คือผ่าน
                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable11_Cash
                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                            chkcredit = False
                            CheckCreditLimit = False
                        End If
                        If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cash_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                            condition = False
                        End If
                    Next
                    If (condition) Then
                        Dim Credit_limit As String = ""
                        If (chkcredit) Then
                            Credit_limit = "Y"
                        Else
                            Credit_limit = "N"
                        End If
                        If (clsfc.InsertSaleOrder(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, EX_BUKRS11_Cash, EX_BELNR11_Cash, EX_GJAHR11_Cash, Bill_Date, conn, tran) > 0) Then
                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_0
                                If (dr.Material <> "") Then
                                    If (clsfc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                End If
                            Next

                        Else
                            condition = False
                        End If
                    End If
                Else
                    'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Sale Order ');", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                End If
            Else
                ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Advanced Payment ');", True)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
            End If
        End If
        If (CustomerTable11_1.Count > 0) Then
            'มี Mat ที่ใช้ Division 11
            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
            ZBABI_VT11.Amount = SumAmount11_1.ToString("############.00")
            ZBABI_VT11.Vat = ((SumAmount11_1 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")

            'ZBABI_BK11.Amount = (CDbl(SumAmount11_1 + CDbl(((SumAmount11_1 * CDbl(ViewState("VAT"))) / 100).ToString("############.00"))) - WHTAmount11_1).ToString("############.00")

            ZBABI_BK11.Amount = (CDbl(SumAmount11_1 + CDbl(((SumAmount11_1 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")))).ToString("############.00")
            ZBABI_BK11.Gl_Account = ddlGL_Account.SelectedValue  'เลขบัญชีต้องดึงจาก Web service Bank
            ZBABI_BK11.Item_Text = Item_Text
            '"20100921"
            If (radioPay.SelectedValue = "CH") Then
                ZBABI_BK11.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
            Else
                ZBABI_BK11.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
            End If
            ZBABI_HD11.Bupla = "N014"
            ZBABI_HD11.Doc_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd") '"20100730"
            ZBABI_HD11.Header_Txt = "R|" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") '"R|LEO GLORY"
            ZBABI_HD11.Pstng_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"

            SAP_Data.Zbapi_Iport_Advanced_Payment(ZBABI_BK11, ZBABI_HD11, Iport_Number, BillTo, ZBABI_VT11, Ex_Belnr11, Ex_Bukrs11, Ex_Gjahr11, CustomerTable11_1, BABITable11)
            Dim xx As String = ""
            For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                xx &= dr.Message & " "
            Next
            If (Ex_Belnr11 <> "") And (Ex_Bukrs11 <> "") And (Ex_Gjahr11 <> "") Then
                'Advanced Payment ผ่าน
                Dim Bill_To As String = ""
                Dim Sold_To As String = ""
                If (Session("PayinBooking").ToString().Split("$")(1) = dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                    Bill_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                    Sold_To = Bill_To
                    If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
                        Bill_To = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
                    End If
                Else
                    Sold_To = Session("PayinBooking").ToString().Split("$")(1)
                    Bill_To = Session("PayinBooking").ToString().Split("$")(1)
                End If

                BABIHEADER11.Doc_Type = "ZSRC"
                If (radioPay.SelectedValue = "CH") Then
                    BABIHEADER11.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Else
                    BABIHEADER11.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                End If
                BABIHEADER11.Sold_To = Sold_To
                BABIHEADER11.Bill_To = Bill_To
                BABIHEADER11.Ship_Name = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                BABIHEADER11.Division = "11"

                SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales(Bill_Date, "", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BELNR11_Cash, EX_BILL_NO11, EX_BUKRS11_Cash, EX_GJAHR11_Cash, EX_SALES_NO11, BABITable11_Cash, SALE_TABLE11_1)
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11_Cash
                    xx &= dr.Message & " "
                Next
                If (EX_SALES_NO11 <> "") Then
                    'Insert Advanced Payment

                    If (clsfc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                            If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Advanced_Payment", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            If (clsfc.InsertSAP_Advanced_Payment(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, ZBABI_BK11.Gl_Account, ZBABI_BK11.Item_Text, ZBABI_BK11.Value_Date, ZBABI_HD11.Bupla, ZBABI_HD11.Doc_Date, ZBABI_HD11.Header_Txt, ZBABI_HD11.Pstng_Date, ZBABI_VT11.Amount, ZBABI_VT11.Vat, Ex_Bukrs11, Ex_Gjahr11, Ex_Belnr11, WHTAmount11_1, "M", conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.ZBAPI_CUSTOMER In CustomerTable11_1
                                    If (dr.Material <> "") Then
                                        If (clsfc.InsertSAP_Advanced_Payment_Material(Iport_Number, dr.Customer, dr.Amount, dr.Item_Text, dr.Material, dr.Price, dr.Quantity, dr.Unit, dr.Wht_Code, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    End If
                                Next
                            Else
                                condition = False
                            End If
                        End If
                    Else
                        condition = False
                    End If

                    'Insert Cash Sale
                    Dim chkcredit As Boolean = True   ' True คือผ่าน
                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable11_Cash
                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                            chkcredit = False
                            CheckCreditLimit = False
                        End If
                        If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cash_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                            condition = False
                        End If
                    Next
                    If (condition) Then
                        Dim Credit_limit As String = ""
                        If (chkcredit) Then
                            Credit_limit = "Y"
                        Else
                            Credit_limit = "N"
                        End If
                        If (clsfc.InsertSaleOrder(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, EX_BUKRS11_Cash, EX_BELNR11_Cash, EX_GJAHR11_Cash, Bill_Date, conn, tran) > 0) Then
                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_1
                                If (dr.Material <> "") Then
                                    If (clsfc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                End If
                            Next

                        Else
                            condition = False
                        End If
                    End If
                Else
                    'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Sale Order ');", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                End If
            Else
                ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Advanced Payment ');", True)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
            End If
        End If
        If (CustomerTable11_5.Count > 0) Then
            'มี Mat ที่ใช้ Division 11
            Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
            ZBABI_VT11.Amount = SumAmount11_5.ToString("############.00")
            ZBABI_VT11.Vat = ((SumAmount11_5 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")

            'ZBABI_BK11.Amount = (CDbl(SumAmount11_5 + CDbl(((SumAmount11_5 * CDbl(ViewState("VAT"))) / 100).ToString("############.00"))) - WHTAmount11_5).ToString("############.00")

            ZBABI_BK11.Amount = (CDbl(SumAmount11_5 + CDbl(((SumAmount11_5 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")))).ToString("############.00")
            ZBABI_BK11.Gl_Account = ddlGL_Account.SelectedValue  'เลขบัญชีต้องดึงจาก Web service Bank
            ZBABI_BK11.Item_Text = Item_Text

            If (radioPay.SelectedValue = "CH") Then
                ZBABI_BK11.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")  '"20100921"
                Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
            Else
                ZBABI_BK11.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"
                Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
            End If
            ZBABI_HD11.Bupla = "N014"
            ZBABI_HD11.Doc_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd") '"20100730"
            ZBABI_HD11.Header_Txt = "R|" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") '"R|LEO GLORY"
            ZBABI_HD11.Pstng_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"

            SAP_Data.Zbapi_Iport_Advanced_Payment(ZBABI_BK11, ZBABI_HD11, Iport_Number, BillTo, ZBABI_VT11, Ex_Belnr11, Ex_Bukrs11, Ex_Gjahr11, CustomerTable11_5, BABITable11)
            Dim xx As String = ""
            For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                xx &= dr.Message & " "
            Next
            If (Ex_Belnr11 <> "") And (Ex_Bukrs11 <> "") And (Ex_Gjahr11 <> "") Then
                'Advanced Payment ผ่าน
                Dim Bill_To As String = ""
                Dim Sold_To As String = ""
                If (Session("PayinBooking").ToString().Split("$")(1) = dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                    Bill_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                    Sold_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                    If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
                        Bill_To = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
                    End If
                Else
                    Sold_To = Session("PayinBooking").ToString().Split("$")(1)
                    Bill_To = Session("PayinBooking").ToString().Split("$")(1)
                End If

                BABIHEADER11.Doc_Type = "ZSRC"
                If (radioPay.SelectedValue = "CH") Then
                    BABIHEADER11.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Else
                    BABIHEADER11.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                End If
                BABIHEADER11.Sold_To = Sold_To
                BABIHEADER11.Bill_To = Bill_To
                BABIHEADER11.Ship_Name = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                BABIHEADER11.Division = "11"

                SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales(Bill_Date, "", Iport_Number, BABIONETIME11, BABIHEADER11, EX_BELNR11_Cash, EX_BILL_NO11, EX_BUKRS11_Cash, EX_GJAHR11_Cash, EX_SALES_NO11, BABITable11_Cash, SALE_TABLE11_5)
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable11_Cash
                    xx &= dr.Message & " "
                Next
                If (EX_SALES_NO11 <> "") Then
                    'Insert Advanced Payment

                    If (clsfc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable11
                            If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Advanced_Payment", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            If (clsfc.InsertSAP_Advanced_Payment(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, ZBABI_BK11.Gl_Account, ZBABI_BK11.Item_Text, ZBABI_BK11.Value_Date, ZBABI_HD11.Bupla, ZBABI_HD11.Doc_Date, ZBABI_HD11.Header_Txt, ZBABI_HD11.Pstng_Date, ZBABI_VT11.Amount, ZBABI_VT11.Vat, Ex_Bukrs11, Ex_Gjahr11, Ex_Belnr11, WHTAmount11_5, "M", conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.ZBAPI_CUSTOMER In CustomerTable11_5
                                    If (dr.Material <> "") Then
                                        If (clsfc.InsertSAP_Advanced_Payment_Material(Iport_Number, dr.Customer, dr.Amount, dr.Item_Text, dr.Material, dr.Price, dr.Quantity, dr.Unit, dr.Wht_Code, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    End If
                                Next
                            Else
                                condition = False
                            End If
                        End If
                    Else
                        condition = False
                    End If

                    'Insert Cash Sale
                    Dim chkcredit As Boolean = True   ' True คือผ่าน
                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable11_Cash
                        If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                            chkcredit = False
                            CheckCreditLimit = False
                        End If
                        If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cash_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                            condition = False
                        End If
                    Next
                    If (condition) Then
                        Dim Credit_limit As String = ""
                        If (chkcredit) Then
                            Credit_limit = "Y"
                        Else
                            Credit_limit = "N"
                        End If
                        If (clsfc.InsertSaleOrder(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, BABIHEADER11.Doc_Type, BABIHEADER11.Req_Date_H, BABIHEADER11.Sold_To, BABIHEADER11.Bill_To, BABIHEADER11.Ship_Name, BABIHEADER11.Division, EX_SALES_NO11, EX_BILL_NO11, Credit_limit, EX_BUKRS11_Cash, EX_BELNR11_Cash, EX_GJAHR11_Cash, Bill_Date, conn, tran) > 0) Then
                            For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE11_5
                                If (dr.Material <> "") Then
                                    If (clsfc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                        condition = False
                                    End If
                                End If
                            Next

                        Else
                            condition = False
                        End If
                    End If
                Else
                    'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Sale Order ');", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                End If
            Else
                ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Advanced Payment ');", True)
                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
            End If
        End If
        If (condition) Then
            If (CustomerTable12_0.Count > 0) Then
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                ZBABI_VT12.Amount = SumAmount12_0.ToString("############.00")
                ZBABI_VT12.Vat = ((SumAmount12_0 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")

                ' ZBABI_BK12.Amount = (CDbl(SumAmount12_0 + CDbl(((SumAmount12_0 * CDbl(ViewState("VAT"))) / 100).ToString("############.00"))) - WHTAmount12_0).ToString("############.00")

                ZBABI_BK12.Amount = (CDbl(SumAmount12_0 + CDbl(((SumAmount12_0 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")))).ToString("############.00")
                ZBABI_BK12.Gl_Account = ddlGL_Account.SelectedValue  'เลขบัญชีต้องดึงจาก Web service Bank
                ZBABI_BK12.Item_Text = Item_Text
                If (radioPay.SelectedValue = "CH") Then
                    ZBABI_BK12.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                    Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Else
                    ZBABI_BK12.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                    Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                End If
                '"20100921"

                ZBABI_HD12.Bupla = "N014"
                ZBABI_HD12.Doc_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100730"
                ZBABI_HD12.Header_Txt = "R|" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") '"R|LEO GLORY"
                ZBABI_HD12.Pstng_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"

                SAP_Data.Zbapi_Iport_Advanced_Payment(ZBABI_BK12, ZBABI_HD12, Iport_Number, BillTo, ZBABI_VT12, Ex_Belnr12, Ex_Bukrs12, Ex_Gjahr12, CustomerTable12_0, BABITable12)
                Dim xx As String = ""
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                    xx &= dr.Message & " "
                Next
                If (Ex_Belnr12 <> "") And (Ex_Bukrs12 <> "") And (Ex_Gjahr12 <> "") Then
                    'Advanced Payment ผ่าน
                    Dim Bill_To As String = ""
                    Dim Sold_to As String = ""
                    If (Session("PayinBooking").ToString().Split("$")(1) = dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                        Bill_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                        Sold_to = Bill_To
                        If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
                            Bill_To = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
                        End If
                    Else
                        Bill_To = Session("PayinBooking").ToString().Split("$")(1)
                        Sold_to = Bill_To
                    End If

                    BABIHEADER12.Doc_Type = "ZSRC"
                    If (radioPay.SelectedValue = "CH") Then
                        BABIHEADER12.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                    Else
                        BABIHEADER12.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                    End If
                    BABIHEADER12.Sold_To = Sold_to
                    BABIHEADER12.Bill_To = Bill_To
                    BABIHEADER12.Ship_Name = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                    BABIHEADER12.Division = "12"

                    SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales(Bill_Date, "", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BELNR12_Cash, EX_BILL_NO12, EX_BUKRS12_Cash, EX_GJAHR12_Cash, EX_SALES_NO12, BABITable12_Cash, SALE_TABLE12_0)
                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable12_Cash
                        xx &= dr.Message & " "
                    Next
                    If (EX_SALES_NO12 <> "") Then
                        'Insert Advanced Payment

                        If (clsfc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                            For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Advanced_Payment", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                If (clsfc.InsertSAP_Advanced_Payment(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, ZBABI_BK12.Gl_Account, ZBABI_BK12.Item_Text, ZBABI_BK12.Value_Date, ZBABI_HD12.Bupla, ZBABI_HD12.Doc_Date, ZBABI_HD12.Header_Txt, ZBABI_HD12.Pstng_Date, ZBABI_VT12.Amount, ZBABI_VT12.Vat, Ex_Bukrs12, Ex_Gjahr12, Ex_Belnr12, WHTAmount12_0, "M", conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.ZBAPI_CUSTOMER In CustomerTable12_0
                                        If (dr.Material <> "") Then
                                            If (clsfc.InsertSAP_Advanced_Payment_Material(Iport_Number, dr.Customer, dr.Amount, dr.Item_Text, dr.Material, dr.Price, dr.Quantity, dr.Unit, dr.Wht_Code, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        End If
                                    Next
                                Else
                                    condition = False
                                End If
                            End If
                        Else
                            condition = False
                        End If

                        'Insert Cash Sale
                        Dim chkcredit As Boolean = True   ' True คือผ่าน
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable12_Cash
                            If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                chkcredit = False
                                CheckCreditLimit = False
                            End If
                            If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cash_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            Dim Credit_limit As String = ""
                            If (chkcredit) Then
                                Credit_limit = "Y"
                            Else
                                Credit_limit = "N"
                            End If
                            If (clsfc.InsertSaleOrder(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, EX_BUKRS12_Cash, EX_BELNR12_Cash, EX_GJAHR12_Cash, Bill_Date, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_0
                                    If (dr.Material <> "") Then
                                        If (clsfc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    End If
                                Next

                            Else
                                condition = False
                            End If
                        End If
                    Else
                        'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Sale Order ');", True)
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                    End If
                Else
                    ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Advanced Payment ');", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                End If
            End If
            If (CustomerTable12_1.Count > 0) Then
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                ZBABI_VT12.Amount = SumAmount12_1.ToString("############.00")
                ZBABI_VT12.Vat = ((SumAmount12_1 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")

                '     ZBABI_BK12.Amount = (CDbl(SumAmount12_1 + CDbl(((SumAmount12_1 * CDbl(ViewState("VAT"))) / 100).ToString("############.00"))) - WHTAmount12_1).ToString("############.00")

                ZBABI_BK12.Amount = (CDbl(SumAmount12_1 + CDbl(((SumAmount12_1 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")))).ToString("############.00")
                ZBABI_BK12.Gl_Account = ddlGL_Account.SelectedValue  'เลขบัญชีต้องดึงจาก Web service Bank
                ZBABI_BK12.Item_Text = Item_Text
                '"20100921"
                If (radioPay.SelectedValue = "CH") Then
                    ZBABI_BK12.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                    Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Else
                    ZBABI_BK12.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                    Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                End If
                ZBABI_HD12.Bupla = "N014"
                ZBABI_HD12.Doc_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd") '"20100730"
                ZBABI_HD12.Header_Txt = "R|" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") '"R|LEO GLORY"
                ZBABI_HD12.Pstng_Date = CDate(ClassFunctionGetData.CDateT((txtDate.Text))).ToString("yyyyMMdd")  '"20100921"

                SAP_Data.Zbapi_Iport_Advanced_Payment(ZBABI_BK12, ZBABI_HD12, Iport_Number, BillTo, ZBABI_VT12, Ex_Belnr12, Ex_Bukrs12, Ex_Gjahr12, CustomerTable12_1, BABITable12)
                Dim xx As String = ""
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                    xx &= dr.Message & " "
                Next
                If (Ex_Belnr12 <> "") And (Ex_Bukrs12 <> "") And (Ex_Gjahr12 <> "") Then
                    'Advanced Payment ผ่าน
                    Dim Bill_To As String = ""
                    Dim Sold_To As String = ""
                    If (Session("PayinBooking").ToString().Split("$")(1) = dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                        Bill_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                        Sold_To = Bill_To
                        If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
                            Bill_To = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
                        End If
                    Else
                        Bill_To = Session("PayinBooking").ToString().Split("$")(1)
                        Sold_To = Bill_To
                    End If

                    BABIHEADER12.Doc_Type = "ZSRC"
                    If (radioPay.SelectedValue = "CH") Then
                        BABIHEADER12.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                    Else
                        BABIHEADER12.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                    End If
                    BABIHEADER12.Sold_To = Sold_To
                    BABIHEADER12.Bill_To = Bill_To
                    BABIHEADER12.Ship_Name = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                    BABIHEADER12.Division = "12"

                    SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales(Bill_Date, "", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BELNR12_Cash, EX_BILL_NO12, EX_BUKRS12_Cash, EX_GJAHR12_Cash, EX_SALES_NO12, BABITable12_Cash, SALE_TABLE12_1)
                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable12_Cash
                        xx &= dr.Message
                    Next
                    If (EX_SALES_NO12 <> "") Then
                        'Insert Advanced Payment

                        If (clsfc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                            For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Advanced_Payment", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                If (clsfc.InsertSAP_Advanced_Payment(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, ZBABI_BK12.Gl_Account, ZBABI_BK12.Item_Text, ZBABI_BK12.Value_Date, ZBABI_HD12.Bupla, ZBABI_HD12.Doc_Date, ZBABI_HD12.Header_Txt, ZBABI_HD12.Pstng_Date, ZBABI_VT12.Amount, ZBABI_VT12.Vat, Ex_Bukrs12, Ex_Gjahr12, Ex_Belnr12, WHTAmount12_1, "M", conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.ZBAPI_CUSTOMER In CustomerTable12_1
                                        If (dr.Material <> "") Then
                                            If (clsfc.InsertSAP_Advanced_Payment_Material(Iport_Number, dr.Customer, dr.Amount, dr.Item_Text, dr.Material, dr.Price, dr.Quantity, dr.Unit, dr.Wht_Code, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        End If
                                    Next
                                Else
                                    condition = False
                                End If
                            End If
                        Else
                            condition = False
                        End If

                        'Insert Cash Sale
                        Dim chkcredit As Boolean = True   ' True คือผ่าน
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable12_Cash
                            If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                chkcredit = False
                                CheckCreditLimit = False
                            End If
                            If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cash_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            Dim Credit_limit As String = ""
                            If (chkcredit) Then
                                Credit_limit = "Y"
                            Else
                                Credit_limit = "N"
                            End If
                            If (clsfc.InsertSaleOrder(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, EX_BUKRS12_Cash, EX_BELNR12_Cash, EX_GJAHR12_Cash, Bill_Date, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_1
                                    If (dr.Material <> "") Then
                                        If (clsfc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    End If
                                Next

                            Else
                                condition = False
                            End If
                        End If
                    Else
                        'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Sale Order ');", True)
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                    End If
                Else
                    ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Advanced Payment ');", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                End If
            End If
            If (CustomerTable12_5.Count > 0) Then
                Iport_Number = Iport_Number.Substring(0, 8) & "-" & (CInt(Iport_Number.Substring(9, 3)) + 1).ToString("000")
                ZBABI_VT12.Amount = SumAmount12_5.ToString("############.00")
                ZBABI_VT12.Vat = ((SumAmount12_5 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")

                '  ZBABI_BK12.Amount = (CDbl(SumAmount12_5 + CDbl(((SumAmount12_5 * CDbl(ViewState("VAT"))) / 100).ToString("############.00"))) - WHTAmount12_5).ToString("############.00")

                ZBABI_BK12.Amount = (CDbl(SumAmount12_5 + CDbl(((SumAmount12_5 * CDbl(ViewState("VAT"))) / 100).ToString("############.00")))).ToString("############.00")
                ZBABI_BK12.Gl_Account = ddlGL_Account.SelectedValue  'เลขบัญชีต้องดึงจาก Web service Bank
                ZBABI_BK12.Item_Text = Item_Text

                If (radioPay.SelectedValue = "CH") Then
                    ZBABI_BK12.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")  '"20100921"
                    Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                Else
                    ZBABI_BK12.Value_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"
                    Bill_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                End If
                ZBABI_HD12.Bupla = "N014"
                ZBABI_HD12.Doc_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd") '"20100730"
                ZBABI_HD12.Header_Txt = "R|" & dsBooking.Tables(0).Rows(0).Item("Vehicle_Text") '"R|LEO GLORY"
                ZBABI_HD12.Pstng_Date = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")  '"20100921"

                SAP_Data.Zbapi_Iport_Advanced_Payment(ZBABI_BK12, ZBABI_HD12, Iport_Number, BillTo, ZBABI_VT12, Ex_Belnr12, Ex_Bukrs12, Ex_Gjahr12, CustomerTable12_5, BABITable12)
                Dim xx As String = ""
                For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                    xx &= dr.Message & " "
                Next
                If (Ex_Belnr12 <> "") And (Ex_Bukrs12 <> "") And (Ex_Gjahr12 <> "") Then
                    'Advanced Payment ผ่าน
                    Dim Bill_To As String = ""
                    Dim Sold_To As String = ""
                    If (Session("PayinBooking").ToString().Split("$")(1) = dsBooking.Tables(0).Rows(0).Item("MAgent_no")) Then
                        Bill_To = dsBooking.Tables(0).Rows(0).Item("MAgent_no")
                        Sold_To = Bill_To
                        If (dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & "" <> "") Then
                            Bill_To = dsBooking.Tables(0).Rows(0).Item("Bill_To_no") & ""
                        End If
                    Else
                        Bill_To = Session("PayinBooking").ToString().Split("$")(1)
                        Sold_To = Bill_To
                    End If

                    BABIHEADER12.Doc_Type = "ZSRC"
                    If (radioPay.SelectedValue = "CH") Then
                        BABIHEADER12.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).AddDays(1).ToString("yyyyMMdd")
                    Else
                        BABIHEADER12.Req_Date_H = CDate(ClassFunctionGetData.CDateT(txtDate.Text)).ToString("yyyyMMdd")
                    End If
                    BABIHEADER12.Sold_To = Sold_To
                    BABIHEADER12.Bill_To = Bill_To
                    BABIHEADER12.Ship_Name = dsBooking.Tables(0).Rows(0).Item("Vehicle_Text")
                    BABIHEADER12.Division = "12"

                    SAP_Data.Zbapi_Iport_Sd_Proc_Cash_Sales(Bill_Date, "", Iport_Number, BABIONETIME12, BABIHEADER12, EX_BELNR12_Cash, EX_BILL_NO12, EX_BUKRS12_Cash, EX_GJAHR12_Cash, EX_SALES_NO12, BABITable12_Cash, SALE_TABLE12_5)

                    For Each dr As SAP_IPORT.BAPIRET1 In BABITable12_Cash
                        xx &= dr.Message & " "
                    Next
                    If (EX_SALES_NO12 <> "") Then
                        'Insert Advanced Payment

                        If (clsfc.InsertIportNumber(Iport_Number, conn, tran) > 0) Then
                            For Each dr As SAP_IPORT.BAPIRET1 In BABITable12
                                If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Advanced_Payment", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                    condition = False
                                End If
                            Next
                            If (condition) Then
                                If (clsfc.InsertSAP_Advanced_Payment(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, ZBABI_BK12.Gl_Account, ZBABI_BK12.Item_Text, ZBABI_BK12.Value_Date, ZBABI_HD12.Bupla, ZBABI_HD12.Doc_Date, ZBABI_HD12.Header_Txt, ZBABI_HD12.Pstng_Date, ZBABI_VT12.Amount, ZBABI_VT12.Vat, Ex_Bukrs12, Ex_Gjahr12, Ex_Belnr12, WHTAmount12_5, "M", conn, tran) > 0) Then
                                    For Each dr As SAP_IPORT.ZBAPI_CUSTOMER In CustomerTable12_5
                                        If (dr.Material <> "") Then
                                            If (clsfc.InsertSAP_Advanced_Payment_Material(Iport_Number, dr.Customer, dr.Amount, dr.Item_Text, dr.Material, dr.Price, dr.Quantity, dr.Unit, dr.Wht_Code, conn, tran) < 1) Then
                                                condition = False
                                            End If
                                        End If
                                    Next
                                Else
                                    condition = False
                                End If
                            End If
                        Else
                            condition = False
                        End If

                        'Insert Cash Sale
                        Dim chkcredit As Boolean = True   ' True คือผ่าน
                        For Each dr As SAP_IPORT.BAPIRET1 In BABITable12_Cash
                            If (dr.Type = "E") And (dr.Id = "VF") And (dr.Number = "140") Then
                                chkcredit = False
                                CheckCreditLimit = False
                            End If
                            If (clsfc.InsertSAP_Table_MESSAGE(Iport_Number, "Zbapi_Iport_Sd_Proc_Cash_Sales", dr.Type, dr.Id, dr.Number, dr.Message, dr.Log_No, dr.Log_Msg_No, dr.Message_V1, dr.Message_V2, dr.Message_V3, dr.Message_V4, conn, tran) < 1) Then
                                condition = False
                            End If
                        Next
                        If (condition) Then
                            Dim Credit_limit As String = ""
                            If (chkcredit) Then
                                Credit_limit = "Y"
                            Else
                                Credit_limit = "N"
                            End If
                            If (clsfc.InsertSaleOrder(Session("PayinBooking").ToString.Split("$")(0), Iport_Number, BABIHEADER12.Doc_Type, BABIHEADER12.Req_Date_H, BABIHEADER12.Sold_To, BABIHEADER12.Bill_To, BABIHEADER12.Ship_Name, BABIHEADER12.Division, EX_SALES_NO12, EX_BILL_NO12, Credit_limit, EX_BUKRS12_Cash, EX_BELNR12_Cash, EX_GJAHR12_Cash, Bill_Date, conn, tran) > 0) Then
                                For Each dr As SAP_IPORT.ZBAPI_SALES_ITEMS In SALE_TABLE12_5
                                    If (dr.Material <> "") Then
                                        If (clsfc.InsertSAP_Sale_Order_Material(Iport_Number, dr.Material, dr.Plant, dr.Target_Qty, dr.Target_Qu, dr.Cond_Type, dr.Discount, dr.Amount, dr.Condvalue, conn, tran) < 1) Then
                                            condition = False
                                        End If
                                    End If
                                Next

                            Else
                                condition = False
                            End If
                        End If
                    Else
                        'ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Sale Order ');", True)
                        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                    End If
                Else
                    ' ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Can not be Create Advanced Payment ');", True)
                    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('" & xx & "');", True)
                End If
            End If
        End If

        If (condition) Then
            clsDB.CommitTran(tran)
            'If (CheckCreditLimit) Then
            '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ทำการสร้าง  Sale Order เรียบร้อย '); parent.closeModal('X');", True)
            'Else
            '    ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('Document cannot be billed due to credit limit check '); parent.closeModal('X');", True)
            'End If
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", " alert('ชำระเงินเรียบร้อย ');", True)
            PanelPayment.Visible = False
            Try
                lbBookingNo.Text = Session("PayinBooking").ToString.Split("$")(0)
            Catch ex As Exception
                lbBookingNo.Text = Session("PayinBooking") & ""
            End Try

            Dim rvNo As String = ""
            If Ex_Belnr11 <> "" Then
                rvNo = Ex_Belnr11
            End If
            If (Ex_Belnr12 <> "") Then
                If (rvNo <> "") Then
                    rvNo &= "<br />" & Ex_Belnr12
                Else
                    rvNo = Ex_Belnr12
                End If
            End If
            lbRVno.Text = rvNo
            lbMOney.Text = ViewState("Amt").ToString() & ""
            PanelDetail.Visible = True
        Else
            clsDB.RollBackTran(tran)
        End If
        Application.UnLock()
        conn.Dispose()
        ClassSAP.SAP_CLOSE(SAP_Data)

        '*************************************************************************************


        Session("PayinBooking") = Nothing
        Session("MAGENT_NAME_BULK") = Nothing
    End Sub

    Private Function GetNameMonth(ByVal Month As String) As String
        Try
            Select Case (CInt(Month).ToString("00"))
                Case "01"
                    Return "Jan"
                Case "02"
                    Return "Feb"
                Case "03"
                    Return "Mar"
                Case "04"
                    Return "Apr"
                Case "05"
                    Return "May"
                Case "06"
                    Return "Jun"
                Case "07"
                    Return "Jul"
                Case "08"
                    Return "Aug"
                Case "09"
                    Return "Sep"
                Case "10"
                    Return "Oct"
                Case "11"
                    Return "Nov"
                Case "12"
                    Return "Dec"
                Case Else
                    Return ""
            End Select
        Catch ex As Exception
            Return Month
        End Try

    End Function

    Private Function Gen_Report(ByVal HeadReport As String, ByVal SoldTo As String, ByVal Shipname As String, ByVal Product As String, ByVal DWT As String, ByVal LOA As String, ByVal TotalProduct As String, ByVal DF As String, ByVal Body As String, ByVal GRT As String) As String
        Dim HTML As String = ""
        Dim dt As DataTable = clsGet.Get_BookingOneRecord(Session("PayinBooking").ToString().Split("$")(0)).Tables(0)
        Dim dTime As String = Date.Now.ToString("dd-MMM-") & Date.Now.ToString("yyyy", New System.Globalization.CultureInfo("en-US"))
        If (dt.Rows.Count > 0) Then
            Try
                Dim Time As String = dt.Rows(0).Item("Marketing_approve").ToString().Split(":")(0)
                dTime = Time.Substring(Time.Length - 3, Time.Length - 1) & " " & GetNameMonth(Time.Substring(Time.Length - 5, Time.Length - 3)) & " " & (CInt(Time.Substring(Time.Length - 9, Time.Length - 5)) - 543)
            Catch ex As Exception

            End Try

        End If

        HTML = "<table width='100%' border='0' cellpadding='0' cellspacing='1'>"
        HTML &= "<tr ><td colspan='6'>" & HeadReport & "</td></tr>"
        HTML &= "<tr ><td style='height:3px;' colspan='6'><img src='../Image/space.gif' /></td></tr>"

        HTML &= "<tr ><td colspan='6'><table width='100%' border='0' cellpadding='0' cellspacing='1'>"
        HTML &= "<tr>"
        HTML &= "<td style='width:140px;' align='left'><font class='White-Style' style='color:#000000'>เรียนผู้จัดการบริษัท :</font>&nbsp;</td>"
        HTML &= "<td style='width:460px;' colspan='4' align='left'><font class='White-Style' style='color:#000000'>" & SoldTo & "</font></td>"
        HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & dTime & "</font></td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:140px;' align='left'><font class='White-Style' style='color:#000000'>Ship Name :</font>&nbsp;</td>"
        HTML &= "<td style='width:120px;' align='left'><font class='White-Style' style='color:#000000'>" & Shipname & "</font></td>"
        HTML &= "<td style='width:120px;' align='left'><font class='White-Style' style='color:#000000'>Product :</font>&nbsp;</td>"
        HTML &= "<td style='width:140px;' align='left'><font class='White-Style' style='color:#000000'>" & Product & "</font></td>"
        HTML &= "<td style='width:80px;' align='left'><font class='White-Style' style='color:#000000'>DWT :</font>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(DWT, 2) & "</font></td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='width:140px;' align='left'><font class='White-Style' style='color:#000000'>L.O.A(Ft.) :</font>&nbsp;</td>"
        HTML &= "<td style='width:120px;' align='left'><font class='White-Style' style='color:#000000'>" & LOA & "</font></td>"
        HTML &= "<td style='width:120px;' align='left'><font class='White-Style' style='color:#000000'>Total Product(MT) :</font>&nbsp;</td>"
        HTML &= "<td style='width:140px;' align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(TotalProduct, 3) & "</font></td>"
        HTML &= "<td style='width:80px;' align='left'>&nbsp;</td>"
        HTML &= "<td align='left'><font class='White-Style' style='color:#000000'>" & FormatNumber(GRT, 2) & " DF(Ft.) " & FormatNumber(DF, 2) & "</font></td>"
        HTML &= "</tr>"

        HTML &= "<tr ><td style='height:3px;' colspan='6'><img src='../Image/space.gif' /></td></tr>"

        HTML &= "<tr ><td colspan='6'>" & Body & "</td></tr>"

        HTML &= "<tr ><td style='height:3px;' colspan='6'><img src='../Image/space.gif' /></td></tr>"

        HTML &= "</table>"
        Return HTML
    End Function

    Private Function Gen_Body(ByVal Vat As String, ByVal DSItem As DataTable) As String
        Dim HTML As String = ""
        HTML = "<table width='100%'  style='border-width: 0px;' border='1' cellpadding='0' cellspacing='0'>"
        Dim Value As Double = 0
        Dim ValueVat As Double = 0
        Dim WHT As Double = 0
        Dim row As Integer = 2
        For Each dr As DataRow In DSItem.Rows
            If (CDbl(dr.Item("data4")) > 0.0) Then
                Dim MatName As String = dr.Item("MAT_NAME") & "<BR /> - " & dr.Item("name")
                If (dr.Item("MAT_NAME") = dr.Item("name")) Then
                    MatName = dr.Item("MAT_NAME")
                End If
                If (row Mod 2) Then
                    HTML &= "<tr>"
                Else
                    HTML &= "<tr style='background-color:#F0F9FB;'>"
                End If
                row += 1
                Dim data1 As String = dr.Item("data1")
                Dim data2 As String = dr.Item("data2")
                Dim data3 As String = dr.Item("data3")
                Dim data4 As String = dr.Item("data4")
                FormatN(data1)
                FormatN(data2)
                FormatN(data3)
                FormatN(data4)
                Dim Matid As String = dr.Item("MATERIAL")
                Try
                    Matid = CInt(Matid)
                Catch ex As Exception

                End Try
                HTML &= "<td style='width:140px;' valign='top'  align='left'><font class='White-Style' style='color:#000000'>" & Matid & "</font>&nbsp;</td>"
                HTML &= "<td style='width:280px;' align='left'><font class='White-Style' style='color:#000000'>" & MatName & "</font></td>"
                HTML &= "<td style='width:80px;' valign='bottom' align='right'><font class='White-Style' style='color:#000000'>" & data1 & "</font>&nbsp;</td>"
                HTML &= "<td style='width:80px;' valign='bottom' align='right'><font class='White-Style' style='color:#000000'>" & data2 & "</font></td>"
                HTML &= "<td style='width:70px;' valign='bottom' align='center'><font class='White-Style' style='color:#000000'>" & data3 & "</font>&nbsp;</td>"
                HTML &= "<td align='right'  valign='bottom'><font class='White-Style' style='color:#000000'>" & data4 & "</font></td>"
                HTML &= "</tr>"
                Value = Value + CDbl(dr.Item("data4"))
                Dim dt As DataTable = clsGet.Get_MeterailWhithodingTax(dr.Item("MATERIAL"))
                If (dt.Rows(0).Item("MAT_WHT") & "" = "01") Or (dt.Rows(0).Item("MAT_WHT") & "" = "02") Or (dt.Rows(0).Item("MAT_WHT") & "" = "03") Then
                    '1%
                    WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 1) / 100).ToString("#########0.00"))).ToString("###############0.00")
                ElseIf (dt.Rows(0).Item("MAT_WHT") & "" = "04") Or (dt.Rows(0).Item("MAT_WHT") & "" = "05") Then
                    '3%
                    WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 3) / 100).ToString("#########0.00"))).ToString("###############0.00")
                ElseIf (dt.Rows(0).Item("MAT_WHT") & "" = "06") Or (dt.Rows(0).Item("MAT_WHT") & "" = "22") Then
                    '5%
                    WHT = (WHT + CDbl(((CDbl(dr.Item("data4")) * 5) / 100).ToString("#########0.00"))).ToString("###############0.00")
                End If
            End If

        Next


        HTML &= "<tr>"
        HTML &= "<td style='border-width: 1px 0px 0px 0px;' colspan='5' align='left'>&nbsp;</td>"
        HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & FormatNumber(Value.ToString("#############0.00")) & "</font></td>"
        HTML &= "</tr>"

        ValueVat = ((Value * CDbl(Vat)) / 100).ToString("############.00")
        HTML &= "<tr>"
        HTML &= "<td style='border-width: 0px;' colspan='5' align='right'><font class='White-Style' style='color:#000000'>Vat " & Vat & "%</font>&nbsp;</td>"
        HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & FormatNumber(ValueVat) & "</font></td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td style='border-width: 0px;' colspan='5' align='right'><font class='White-Style' style='color:#000000'>รวมประเมินค่าใช้จ่าย</font>&nbsp;</td>"
        HTML &= "<td align='right'><font class='White-Style' style='color:#000000'>" & FormatNumber((Value + ValueVat).ToString("###############.00")) & "</font></td>"
        HTML &= "</tr>"

        HTML &= "</table>"

        HTML &= Gen_Sum(Value.ToString("#############0.00"), ValueVat.ToString(), WHT.ToString())
        ViewState("DSItem") = DSItem
        Return HTML
    End Function

    Private Sub FormatN(ByRef data As String)
        Try
            data = FormatNumber(data, 2)
        Catch ex As Exception

        End Try
    End Sub

    Private Function Gen_Sum(ByVal Net As String, ByVal Vat As String, ByVal WHT As String) As String
        Dim HTML As String = ""

        HTML = "<table width='100%' border='0' cellpadding='0' cellspacing='1'>"

        HTML &= "<tr><td colspan='6'>&nbsp;</td></tr>"

        HTML &= "<tr>"
        HTML &= "<td>&nbsp;</td>"
        HTML &= "<td style='width:130px; background-color:#aeaeae;' align='center'><font class='White-Style' style='color:#000000'>NET</font></td>"
        HTML &= "<td style='width:130px; background-color:#aeaeae;' align='center'><font class='White-Style' style='color:#000000'>VAT</font></td>"
        HTML &= "<td style='width:130px; background-color:#aeaeae;' align='center'><font class='White-Style' style='color:#000000'>WITHHOLDING</font>&nbsp;</td>"
        HTML &= "<td style='width:130px; background-color:#aeaeae;' align='center'><font class='White-Style' style='color:#000000'>ยอดเงินที่ต้องชำระ</font></td>"
        HTML &= "<td>&nbsp;</td>"
        HTML &= "</tr>"

        HTML &= "<tr>"
        HTML &= "<td>&nbsp;</td>"
        HTML &= "<td style='width:130px; background-color:#e7f9ff;' align='center'><font class='White-Style' style='color:#000000'>" & FormatNumber(Net, 2) & "</font></td>"
        HTML &= "<td style='width:130px; background-color:#e7f9ff;' align='center'><font class='White-Style' style='color:#000000'>" & FormatNumber(Vat, 2) & "</font></td>"
        HTML &= "<td style='width:130px; background-color:#e7f9ff;' align='center'><font class='White-Style' style='color:#000000'>" & FormatNumber(WHT, 2) & "</font>&nbsp;</td>"
        HTML &= "<td style='width:130px; background-color:#e7f9ff;' align='center'><font class='White-Style' style='color:#000000'>" & FormatNumber(((CDbl(Net) + CDbl(Vat)) - CDbl(WHT)).ToString("#############0.00"), 2) & "</font></td>"
        HTML &= "<td>&nbsp;</td>"
        HTML &= "</tr>"
        ViewState("WHTFORREPORT") = FormatNumber(WHT, 2)
        ViewState("NET_AMOUNT_") = FormatNumber(((CDbl(Net) + CDbl(Vat)) - CDbl(WHT)).ToString("#############0.00"), 2)
        ViewState("Amt") = FormatNumber(((CDbl(Net) + CDbl(Vat)) - CDbl(WHT)).ToString("#############0.00"), 2)
        HTML &= "</table>"
        Return HTML
    End Function

    Private Sub radioPay_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles radioPay.SelectedIndexChanged
        If (radioPay.SelectedValue = "CH") Then
            rowCH.Visible = True
        Else
            rowCH.Visible = False
        End If
    End Sub

    Private Sub ddlBank_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlBank.SelectedIndexChanged
        If ddlBank.SelectedValue = "0" Then
            ddlGL_Account.Items.Insert(0, "<--กรุณาทำการเลือกธนาคาร-->")
            ddlGL_Account.Items(0).Value = "0"
        Else
            Dim ds As DataTable = clsGet.Get_GL(ddlBank.SelectedValue, "")
            If (ds.Rows.Count > 0) Then
                With ddlGL_Account
                    .ClearSelection()
                    .Items.Clear()
                    .DataTextField = "Gl_Name"
                    .DataValueField = "Gl_Account"
                    .DataSource = ds
                    .DataBind()
                    .Items.Insert(0, "<--กรุณาเลือก GL Account-->")
                    .Items(0).Value = "0"
                End With
            End If

        End If
    End Sub

    Private Sub btnCloseDetail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCloseDetail.Click
        Session("MAGENT_NAME_BULK") = Nothing
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "  parent.closeModal('X');", True)
    End Sub


    Private Sub MainPage_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        Dim ds As DataSet = Session("UserData")
        If Not (ds Is Nothing) Then
            Page.MasterPageFile = clsGet.GetMaster_Page(ds.Tables(0).Rows(0).Item("User_Name").ToString(), "")
        End If
    End Sub

    Private Function CreateDataTableForReport()
        Dim dt As New DataTable
        dt.Columns.Add("MATERIAL", GetType(String))
        dt.Columns.Add("Text_line", GetType(String))
        dt.Columns.Add("data1", GetType(String))
        dt.Columns.Add("data2", GetType(String))
        dt.Columns.Add("data3", GetType(String))
        dt.Columns.Add("data4", GetType(String))
        dt.AcceptChanges()
        Return dt
    End Function

    Private Sub btnPrintEs_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrintEs.Click
        Dim service As New _ReportingService.Report

        Dim optWindow As String = "left=0,top=0,location=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,toolbar=no"
        Dim Orientation As Boolean = True
        Dim ReportName As String = String.Empty
        Dim reportDataSource As String = String.Empty
        Dim paraName As String = String.Empty
        Dim paraValue As String = String.Empty
        Dim reportType As String = String.Empty
        Dim urlDisplay As String = String.Empty
        Dim dsReport As New DataSet

        Dim Vat As String = ""
        Dim dsConfig As DataSet = Session("Config")
        If (dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(1) = "00") Then
            Vat = CInt(dsConfig.Tables(0).Rows(0).Item("Vat").ToString().Split(".")(0)).ToString()
        Else
            Vat = dsConfig.Tables(0).Rows(0).Item("Vat").ToString()
        End If


        Dim dt As DataTable = CreateDataTableForReport()
        Dim dSITem As DataTable = ViewState("DSItem")
        For Each dr As DataRow In dSITem.Rows
            Dim dn As DataRow = dt.NewRow
            dn.Item("MATERIAL") = dr.Item("Material")
            dn.Item("Text_line") = dr.Item("MAT_NAME")
            dn.Item("data1") = dr.Item("data1")
            dn.Item("data2") = dr.Item("data2")
            dn.Item("data3") = dr.Item("data3")
            dn.Item("data4") = dr.Item("data4")
            dt.Rows.Add(dn)
            dt.AcceptChanges()
        Next
        If dt.Rows.Count > 0 Then

            dt.Columns.Add("VAT", GetType(String))
            dt.Columns.Add("VAT_AMOUNT", GetType(String))
            dt.Columns.Add("NET", GetType(String))
            dt.Columns.Add("AMOUNT", GetType(String))
            dt.Columns.Add("Text_AMOUNT", GetType(String))
            dt.AcceptChanges()
            Dim NET As Double = 0.0
            For i As Integer = 0 To dt.Rows.Count - 1
                NET = NET + CDbl(CDbl(dt.Rows(i).Item("data4")).ToString("##############0.00"))
            Next
            Dim VAT_AMOUNT As String = ((NET * CDbl(Vat)) / 100).ToString("############.00")
            Dim AMOUNT As String = NET + CDbl(((NET * CDbl(Vat)) / 100).ToString("############.00"))
            Dim Text_AMOUNT As String = ConvertMoneyToText((NET + CDbl(((NET * CDbl(Vat)) / 100).ToString("############.00"))).ToString())
            For i As Integer = 0 To dt.Rows.Count - 1
                Dim MAT As String = ""
                Try
                    MAT = CInt(dt.Rows(i).Item("MATERIAL"))
                Catch ex As Exception
                    MAT = dt.Rows(i).Item("MATERIAL")
                End Try
                dt.Rows(i).Item("MATERIAL") = MAT
                dt.Rows(i).Item("VAT") = Vat
                dt.Rows(i).Item("VAT_AMOUNT") = FormatNumber(VAT_AMOUNT, 2)
                dt.Rows(i).Item("NET") = FormatNumber(NET, 2)
                dt.Rows(i).Item("AMOUNT") = FormatNumber(AMOUNT, 2)
                dt.Rows(i).Item("Text_AMOUNT") = Text_AMOUNT
                Try
                    dt.Rows(i).Item("data1") = FormatNumber(dt.Rows(i).Item("data1"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data2") = FormatNumber(dt.Rows(i).Item("data2"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data3") = FormatNumber(dt.Rows(i).Item("data3"), 2)
                Catch ex As Exception

                End Try
                Try
                    dt.Rows(i).Item("data4") = FormatNumber(dt.Rows(i).Item("data4"), 2)
                Catch ex As Exception

                End Try
                dt.AcceptChanges()
            Next
            dsReport.Tables.Add(dt.Copy)
            dsReport.AcceptChanges()
            ReportName = "Estimate_For_Finance.rdlc"
            ' dsReport = New DataSet
            reportDataSource = "Actual_Report_Actual"

            dt = clsGet.Get_BookingOneRecord(dSITem.Rows(0).Item("Booking_no")).Tables(0)


            paraName = "SHIP;PERIOD;LAYTIME;AGENT;LOA;GRT;DWT;PO;WHARF;Booking_no;WHT;NET_AMOUNT;RV_no;Type_Pay;Bank;Account;Date_Pay"
            If (dt.Rows.Count > 0) Then
                Dim PORT As String = dt.Rows(0).Item("PORT")
                Dim LAYTIME As String = dt.Rows(0).Item("Lay_Time")
                Dim MAGEnt_Name As String = Session("MAGENT_NAME_BULK")

                Dim dtwh As DataTable = clsGet.Get_BookingWharf(dSITem.Rows(0).Item("Booking_no"))
                Dim WHARF As String = dtwh.Rows(0).Item("Wharf")
                Dim PERIOD As String = ""
                PERIOD &= ""
                Dim type_pay As String = "โอน"
                If (radioPay.SelectedValue = "CH") Then
                    type_pay = "เช็ค"
                End If
                paraValue = dt.Rows(0).Item("Vehicle_Text") & "" & ";" & PERIOD & ";" & LAYTIME & ";" & MAGEnt_Name & ";" & dt.Rows(0).Item("Vehicle_LOA") & "" & ";" & dt.Rows(0).Item("Vehicle_GRT") & ";" & dt.Rows(0).Item("Vehicle_DWT") & ";" & dt.Rows(0).Item("Product_Amount") & ";" & WHARF & ";" & dSITem.Rows(0).Item("Booking_no") & ";" & ViewState("WHTFORREPORT") & ";" & ViewState("NET_AMOUNT_") & ";" & lbRVno.Text & ";" & type_pay & ";" & ddlBank.SelectedItem.Text & ";" & ddlGL_Account.SelectedItem.Text & ";" & txtDate.Text
            Else
                paraValue = ";;;;;;;;;;;;;;;;"
            End If

            Orientation = True
            reportType = "pdf"

            Try
                urlDisplay = service.CreateReporting(dsReport, reportDataSource, reportType, ReportName, paraName, paraValue, Orientation, "")

                ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "window.open('" + urlDisplay + "','_blank','" + optWindow + "');", True)
            Catch ex As Exception
                Dim errortxt As String = ex.Message
            End Try
        Else
            ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "myscript", "alert('ไม่พบรายการ Invoice');", True)
        End If
    End Sub

    Private Function ConvertMoneyToText(ByVal Money As String) As String
        Dim Digit As String = Money.Split(".")(0)
        Dim SubMoney As String
        Try
            SubMoney = Money.Split(".")(1)
        Catch ex As Exception
            SubMoney = "00"
        End Try
        Dim COuntLength As Int16 = Digit.Length

        Dim TxtMoney As String = ""

        For i As Integer = 0 To COuntLength - 1
            If (COuntLength > 7) Then
                Select Case (Digit.Substring(0, 1).ToString())
                    Case "9" : TxtMoney &= "เก้า"
                    Case "8" : TxtMoney &= "แปด"
                    Case "7" : TxtMoney &= "เจ็ด"
                    Case "6" : TxtMoney &= "หก"
                    Case "5" : TxtMoney &= "ห้า"
                    Case "4" : TxtMoney &= "สี่"
                    Case "3" : TxtMoney &= "สาม"
                    Case "2" : TxtMoney &= "สอง"
                    Case "1" : TxtMoney &= "หนึ่ง"
                End Select

                Select Case (COuntLength.ToString)
                    Case "13" : TxtMoney &= "ล้านล้าน"
                    Case "12" : TxtMoney &= "แสนล้าน"
                    Case "11" : TxtMoney &= "หมื่นล้าน"
                    Case "10" : TxtMoney &= "พันล้าน"
                    Case "9" : TxtMoney &= "ร้อยล้าน"
                    Case "8" : TxtMoney &= "สิบล้าน"
                End Select
            Else
                Select Case (Digit.Substring(0, 1).ToString())
                    Case "9" : TxtMoney &= "เก้า"
                    Case "8" : TxtMoney &= "แปด"
                    Case "7" : TxtMoney &= "เจ็ด"
                    Case "6" : TxtMoney &= "หก"
                    Case "5" : TxtMoney &= "ห้า"
                    Case "4" : TxtMoney &= "สี่"
                    Case "3" : TxtMoney &= "สาม"
                    Case "2"
                        If (COuntLength.ToString() = "2") Then
                            TxtMoney &= "ยี่"
                        Else
                            TxtMoney &= "สอง"
                        End If

                    Case "1"
                        If (COuntLength.ToString() = "2") Then
                            TxtMoney &= "เอ็ด"
                        Else
                            TxtMoney &= "หนึ่ง"
                        End If
                End Select

                Select Case (COuntLength.ToString)
                    Case "7" : TxtMoney &= "ล้าน"
                    Case "6" : TxtMoney &= "แสน"
                    Case "5" : TxtMoney &= "หมื่น"
                    Case "4" : TxtMoney &= "พัน"
                    Case "3" : TxtMoney &= "ร้อย"
                    Case "2" : TxtMoney &= "สิบ"
                    Case "1" : TxtMoney &= "บาท"
                End Select
            End If
            Select Case (COuntLength.ToString())
                Case "13"
                    Digit = CInt(Digit) Mod 1000000000000
                Case "12"
                    Digit = CInt(Digit) Mod 100000000000
                Case "11"
                    Digit = CInt(Digit) Mod 10000000000
                Case "10"
                    Digit = CInt(Digit) Mod 1000000000
                Case "9"
                    Digit = CInt(Digit) Mod 100000000
                Case "8"
                    Digit = CInt(Digit) Mod 10000000
                Case "7"
                    Digit = CInt(Digit) Mod 1000000
                Case "6"
                    Digit = CInt(Digit) Mod 100000
                Case "5"
                    Digit = CInt(Digit) Mod 10000
                Case "4"
                    Digit = CInt(Digit) Mod 1000
                Case "3"
                    Digit = CInt(Digit) Mod 100
                Case "2"
                    Digit = CInt(Digit) Mod 10
                Case "1"
                    Digit = CInt(Digit) Mod 1
            End Select
            COuntLength -= 1
        Next
        If (SubMoney <> "00") Then
            If (SubMoney.Length = 2) Then
                Select Case (SubMoney.Substring(0, 1))
                    Case "9" : TxtMoney &= "เก้าสิบ"
                    Case "8" : TxtMoney &= "แปดสิบ"
                    Case "7" : TxtMoney &= "เจ็ดสิบ"
                    Case "6" : TxtMoney &= "หกสิบ"
                    Case "5" : TxtMoney &= "ห้าสิบ"
                    Case "4" : TxtMoney &= "สี่สิบ"
                    Case "3" : TxtMoney &= "สามสิบ"
                    Case "2" : TxtMoney &= "ยี่สิบ"
                    Case "1" : TxtMoney &= "สิบ"
                End Select
                Select Case (SubMoney.Substring(1, 1))
                    Case "9" : TxtMoney &= "เก้าสตางค์"
                    Case "8" : TxtMoney &= "แปดสตางค์"
                    Case "7" : TxtMoney &= "เจ็ดสตางค์"
                    Case "6" : TxtMoney &= "หกสตางค์"
                    Case "5" : TxtMoney &= "ห้าสตางค์"
                    Case "4" : TxtMoney &= "สี่สตางค์"
                    Case "3" : TxtMoney &= "สามสตางค์"
                    Case "2" : TxtMoney &= "สองสตางค์"
                    Case "1"
                        If (SubMoney.Length = 2) Then
                            If (SubMoney.Substring(0, 1) = "0") Then
                                TxtMoney &= "หนึ่งสตางค์"
                            Else
                                TxtMoney &= "เอ็ดสตางค์"
                            End If

                        Else
                            TxtMoney &= "หนึ่งสตางค์"
                        End If
                End Select
            Else
                Select Case (SubMoney.Substring(0, 1))
                    Case "9" : TxtMoney &= "เก้าสิบสตางค์"
                    Case "8" : TxtMoney &= "แปดสิบสตางค์"
                    Case "7" : TxtMoney &= "เจ็ดสิบสตางค์"
                    Case "6" : TxtMoney &= "หกสิบสตางค์"
                    Case "5" : TxtMoney &= "ห้าสิบสตางค์"
                    Case "4" : TxtMoney &= "สี่สิบสตางค์"
                    Case "3" : TxtMoney &= "สามสิบสตางค์"
                    Case "2" : TxtMoney &= "ยี่สิบสตางค์"
                    Case "1" : TxtMoney &= "สิบสตางค์"
                End Select
            End If
        End If
        Return TxtMoney
    End Function

End Class